const express = require('express');
const mongoose = require('mongoose');

const app = express();


// 连接数据库
mongoose.connect('mongodb://localhost:27017/blog', {
    useCreateIndex: true,
    useNewUrlParser: true,
    useUnifiedTopology: true
})

const Article = mongoose.model('Article', new mongoose.Schema({
    title: { type: String },
    body: { type: String }
}));


app.use(require('cors')());
app.use(express.json());

app.get('/', async(req, res) => {
    res.send('hello');
})

// 新建文章
app.post('/api/articles', async(req, res) => {
    const article = await Article.create(req.body);
    res.send(article);
})

// 文章列表
app.get('/api/articles', async(req, res) => {
    const article = await Article.find();
    res.send(article);
});

// 删除文章
app.delete('/api/articles/:id', async(req, res) => {
    await Article.findByIdAndDelete(req.params.id);
    res.send({
        status: 'success'
    });
});

// 文章详情
app.get('/api/articles/:id', async(req, res) => {
    const article = await Article.findById(req.params.id);
    res.send(article);
});

// 文章修改
app.put('/api/articles/:id', async(req, res) => {
    const article = await Article.findByIdAndUpdate(req.params.id, req.body);
    res.send(article);
});

app.listen(3001, () => {
    console.log('http://localhost:3001');
})